package com.bdqn.jpathymeleaf.controller;


import com.bdqn.jpathymeleaf.service.IRoleService;
import com.bdqn.jpathymeleaf.service.UserService;
import com.bdqn.jpathymeleaf.pojo.Role;
import com.bdqn.jpathymeleaf.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    /*    @Resource
        private UserService userService;
        @RequestMapping(value = "/getUser",method = RequestMethod.GET)
        public User getUser(Long usrId){
            User user=userService.getUer(usrId);
            return user;
        }*/
    @Resource
    private UserService userService;
    private IRoleService roleService;

    @RequestMapping(value = "/users")
    public List<User> findAllUsers() {
        List<User> list = userService.findAllUsers();
        return list;
    }

    @GetMapping(value = "/user/{id}")
    public User getUser(@PathVariable("id") Long userId) {
        User user = userService.getUer(userId);
        return user;
    }

    @PostMapping(value = "/user")
    private void addUser(User user) {
        userService.addUser(user);
    }

    @PutMapping(value = "/user")
    public void updateUser(User user) {
        userService.updateUser(user);
    }

    @DeleteMapping(value = "/user/{id}")
    public void deleteUser(@PathVariable("id") Long userId) {
        userService.deleteUser(userId);
    }

/*    @RequestMapping(value = "/user/list")
    public String list(Model model, String userName, @RequestParam(required = false, defaultValue = "0") Long roleId, @RequestParam(required = false, defaultValue = "1") int pageIndex) {

        Sort sort = new Sort(Sort.Direction.ASC, "userId");
        Pageable pageable = new PageRequest(pageIndex - 1, 5, sort);
        Page<User> userPage = userService.findAllUsers(userName, roleId, pageable);
        model.addAttribute("userPage", userPage);
        model.addAttribute("userName", userName);
        model.addAttribute("roleId", roleId);
        List<Role> roles = IRoleService.findAllRole();
        model.addAttribute("roles", roles);
        return "user/list";
    }*/

    @RequestMapping(value = "/user/add")
    public String add(Model model) {
        List<Role> roles = roleService.findAllRole();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    @RequestMapping(value = "/user/save")
    public String save(User user) {
        /* userService.saveUser(user);*/
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/user/edit")
    public String edit(Long usrId, Model model) {
        User user = userService.getUer(usrId);
        List<Role> roles = roleService.findAllRole();
        model.addAttribute("roles", roles);
        model.addAttribute("user", user);
        return "user/edit";
    }
}
